local _util = {}

_util.callback = function(topic, message)  -- string
    --print("Topic: " .. topic .. ", message: '" .. message .. "'")
    --mqtt_client:publish(args.topic_p, message)
    redis_util.redis_cmd('session',"set","mqtt_message", "t:"..topic.." m:"..message)
end

--EMQ添加用户名和密码
_util.add_emq_user = function(user, passwd, expire_time)
    if not common_util.check_args(2, user, passwd) then
        return nil
    end
    local key = "mqtt_user:" .. user
    local session_data, boo = redis_util.redis_cmd('emq' ,"hmset", key, "password", passwd)
    if false == boo then
        return nil
    end
    local expire_time_num = tonumber(expire_time)
    if expire_time_num then
        redis_util.redis_cmd('emq' ,"expire", key, expire_time_num)
    end
    return true
end

--EMQ添加用户ACL权限
--@acl "pub", "sub", "pubsub"
--@expire_time 存活时间 
_util.add_user_acl = function(user, topic, acl, expire_time)
    local acl_map = {
        ["sub"] = 1,
        ["pub"] = 2,
        ["subpub"] = 3,
    }
    if not common_util.check_args(3, user, acl, topic) then
        return nil
    end
    local key = "mqtt_acl:" .. user
    local session_data, boo = redis_util.redis_cmd('emq' ,"hmset", key, topic, acl_map[acl])
    if false == boo then
        return nil
    end
    local expire_time_num = tonumber(expire_time)
    if expire_time_num then
        redis_util.redis_cmd('emq' ,"expire", key, expire_time_num)
    end
    return true
end

_util.get_device_authority = function(device_id, gateway_id, user_id)
    local sql = "select authority from tb_user_device_info where user_id=" .. user_id .. " and status!=0 and device_id="..ngx.quote_sql_str(device_id).." and gateway_id="..ngx.quote_sql_str(gateway_id).." limit 1"
    local data,bool = common_util.db_query_common(sql,common_config.db_user_info_addr)
    if false == bool  then
        --connection:over()
        common_util.exit(200, 0, nil, "500", "mysql is error")
    end
    if next(data) then
        local authority = tonumber(data[1]["authority"])
        if 0 == authority then
            return nil
        end
        local res_data = {
            ["is_view"] = bit.band(authority, 1) > 0,
            ["is_control"] = bit.band(authority, 2) > 0,
            ["is_manage"] = bit.band(authority, 4) > 0,
        }
        return res_data
    end
    return nil
end

--发布绑定消息
_util.band_device = function(gateway_id, signature)
    local data = {
        ["content_type"] = "band",
        ["data"] = {
            ["user_type"] = "wechat",
            ["signature"] = signature,
        }
    }
    mqtt_util.publish(gateway_id .. "/" .. common_config.mqtt_config.change_topic, cjson_safe.encode(data))
end

--发布控制设备类消息
_util.control_device = function(gateway_id, device_id, control_type, control_value)
    local data = {
        ["content_type"] = "control",
        ["data"] = {
            ["device_id"] = device_id,
            ["control_type"] = control_type,
            ["control_value"] = control_value,
        }
    }
    mqtt_util.publish(gateway_id .. "/" .. common_config.mqtt_config.change_topic, cjson_safe.encode(data))
end

--发布主题消息
_util.publish = function(topic, message)
    local tal = {
        ["topic"] = topic,
        ["message"] = message,
    }
    local result,boo = redis_util.redis_cmd('session',"lpush", "mqtt_publish", cjson.encode(tal))
    if not boo then
        -- local date=os.date("%Y-%m-%d %H:%M:%S")
        local logmsg = "Status:  "..boo
        ngx.log(ngx.DEBUG, logmsg)
    else
        -- local date=os.date("%Y-%m-%d %H:%M:%S")
        local logmsg = "Status:  "..boo.."  Result:  "..result
        ngx.log(ngx.DEBUG, logmsg)
    end
end

--验证设备身份
--@device_id 设备ID
--@gateway_id 设备所属网关ID
--@signature_in 网关签名
_util.verify_device = function(gateway_id, signature_in)
    if  "string" ~= type(gateway_id) then
        return nil
    end
    local key = "device_" .. gateway_id 
    local signature, boo = redis_util.redis_cmd('session' ,"get", key)
    if "string" ~= type(signature) then
        local sql = "select signature from tb_gateway_info where status!= 0 and gateway_id="..ngx.quote_sql_str(gateway_id) .. " limit 1"
        local data,bool = common_util.db_query_common(sql,common_config.db_user_info_addr)
        if false == bool  then
            --connection:over()
            common_util.exit(200, 0, nil, "500", "mysql is error")
        end
        if next(data) then
            signature = data[1].signature
            --将网关签名存入缓存
            redis_util.redis_cmd('session' ,"setex", signature, 86400, key)
        end
    end
    return signature_in == signature
end

--清除网关的缓存
_util.delete_gateway_cache = function(gateway_id)
    if "string" ~= type(gateway_id) then
        return nil
    end
    redis_util.redis_cmd('session' ,"del", "device_" .. gateway_id)
    redis_util.redis_cmd('session' ,"del", "mqtt_user:" .. gateway_id)
    redis_util.redis_cmd('session' ,"del", "mqtt_acl:" .. gateway_id)
end

--获取设备信息
_util.get_device_detail_info = function(device_id, gateway_id)
    local sql = "select * from tb_device_common_info where device_id=".. ngx.quote_sql_str(device_id).." and gateway_id="..ngx.quote_sql_str(gateway_id).." limit 1"
    local data,bool = common_util.db_query_common(sql,common_config.db_user_info_addr)
    if true ~= bool then
        return nil
    end
    if next(data) then
        return data[1]
    end
    return nil
end

--根据device_id获取用户设备信息
_util.get_device_info_by_deviceid_uid = function(device_id, gateway_id, user_id)
    local sql = "select * from tb_user_device_info where device_id=".. ngx.quote_sql_str(device_id).." and status != 0 and user_id="..user_id.." and gateway_id="..ngx.quote_sql_str(gateway_id) .." limit 1"
    local data,bool = common_util.db_query_common(sql,common_config.db_user_info_addr)
    if true ~= bool then
        return nil
    end
    if next(data) then
        return data[1]
    end
    return nil
end

return _util